package com.zealcomm.ivcscustomer.widget

import android.content.Context
import android.graphics.PointF
import android.graphics.Rect
import android.text.TextUtils
import android.util.AttributeSet
import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil
import cn.bingoogolapple.qrcode.core.ScanResult
import cn.bingoogolapple.qrcode.zxing.ZXingView
import com.google.zxing.*
import com.google.zxing.common.GlobalHistogramBinarizer
import com.google.zxing.common.HybridBinarizer

/**
 * 用于获取扫码成功后码的格式（二维码，条形码等）
 */
class ZXingViewWrap : ZXingView {

    var format:String? = null
    var barcodeFormat:BarcodeFormat? = null

    constructor(context: Context, attributeSet: AttributeSet) : this(context, attributeSet, 0) {}
    constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(
        context,
        attributeSet,
        defStyleAttr
    ) {
    }

    override fun processData(
        data: ByteArray?,
        width: Int,
        height: Int,
        isRetry: Boolean
    ): ScanResult? {
        var rawResult: Result? = null
        var scanBoxAreaRect: Rect? = null
        val field = ZXingView::class.java.getDeclaredField("mMultiFormatReader")
        field.isAccessible = true
        var mMultiFormatReader = field.get(this) as MultiFormatReader
        try {
            val source: PlanarYUVLuminanceSource
            scanBoxAreaRect = mScanBoxView.getScanBoxAreaRect(height)
            source = if (scanBoxAreaRect != null) {
                PlanarYUVLuminanceSource(
                    data,
                    width,
                    height,
                    scanBoxAreaRect.left,
                    scanBoxAreaRect.top,
                    scanBoxAreaRect.width(),
                    scanBoxAreaRect.height(),
                    false
                )
            } else {
                PlanarYUVLuminanceSource(data, width, height, 0, 0, width, height, false)
            }
            rawResult =
                mMultiFormatReader.decodeWithState(BinaryBitmap(GlobalHistogramBinarizer(source)))
            if (rawResult == null) {
                rawResult =
                    mMultiFormatReader.decodeWithState(BinaryBitmap(HybridBinarizer(source)))
                if (rawResult != null) {
                    BGAQRCodeUtil.d("GlobalHistogramBinarizer 没识别到，HybridBinarizer 能识别到")
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            mMultiFormatReader.reset()
        }

        if (rawResult == null) {
            return null
        }

        val result = rawResult.text
        if (TextUtils.isEmpty(result)) {
            return null
        }

        barcodeFormat = rawResult.barcodeFormat
        BGAQRCodeUtil.d("格式为：" + barcodeFormat!!.name)
        format = barcodeFormat!!.name
        // 处理自动缩放和定位点

        // 处理自动缩放和定位点
        val isNeedAutoZoom = isNeedAutoZoom(barcodeFormat!!)
        if (isShowLocationPoint || isNeedAutoZoom) {
            val resultPoints = rawResult.resultPoints
            val pointArr = arrayOfNulls<PointF>(resultPoints.size)
            var pointIndex = 0
            for (resultPoint in resultPoints) {
                pointArr[pointIndex] = PointF(resultPoint.x, resultPoint.y)
                pointIndex++
            }
            if (transformToViewCoordinates(pointArr, scanBoxAreaRect, isNeedAutoZoom, result)) {
                return null
            }
        }
        return ScanResult(result)
    }

    private fun isNeedAutoZoom(barcodeFormat: BarcodeFormat): Boolean {
        return isAutoZoom && barcodeFormat == BarcodeFormat.QR_CODE
    }
}